package com.cn.web.controller.mc;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.cn.bean.dto.MoxiaoDto;
import com.cn.bean.pojo.bc.User;
import com.cn.bean.pojo.mc.*;
import com.cn.config.config.Result;
import com.cn.service.server.bc.MaterialServer;
import com.cn.service.server.mc.HcxxService;
import com.cn.service.server.mc.K3WlXxSQServer;
import com.cn.service.server.mc.McYcService;
import com.cn.service.server.mc.MoXiaoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@CrossOrigin
@RestController
public class MoXiaoController {
    @Autowired
    private MoXiaoService moXiaoService;
    @Autowired
    private MaterialServer materialServer;
    @Autowired
    private K3WlXxSQServer k3WlXxSQServer;
    @Autowired(required = false)
    private McYcService mcYcService;
    @Autowired
    private HcxxService hcxxService;

    @RequestMapping("/select/Allmoxiao")
    @ResponseBody
    public List<MoxiaoDto> selectMoXiao(@RequestBody JSONObject jsonObject) {
        Integer page = jsonObject.getInteger("page");
        Integer limit = jsonObject.getInteger("limit");
        String lx = jsonObject.getString("lx");
        String djBh = jsonObject.getString("djBh");
        String djZt = jsonObject.getString("djZt");
        lx = (lx != null) ? lx : "";
        djBh = (djBh != null) ? djBh : "";
        List<MoxiaoDto> moxiaoDtoList = moXiaoService.selectAllMoXiao(limit, page, djBh, lx, djZt);
        return moxiaoDtoList;
    }

    @RequestMapping("/select/All")
    @ResponseBody
    public List<McMx> selectAll(@RequestBody JSONObject jsonObject) {

        Integer page = jsonObject.getInteger("page");
        Integer limit = jsonObject.getInteger("limit");
        String id = jsonObject.getString("id");
        String gx = jsonObject.getString("gx");
        Integer zt = jsonObject.getInteger("zt");
        gx = (id != null) ? gx : "";
        id = (id != null) ? id : "";
        List<McMx> mcMx = moXiaoService.getMcMx(limit, page, id, gx, zt);
//        String lx = jsonObject.getString("lx");
//        String djBh = jsonObject.getString("djBh");
//        Integer zt = jsonObject.getInteger("zt");
//        lx = (lx != null) ? lx : "";
//        djBh = (djBh != null) ? djBh : "";
//        List<K3FlXx> moxiaoDtoList = moXiaoService.selectAll(limit, page, djBh, lx, zt);
        return mcMx;
    }

    /**
     * 更改磨削状态
     */
    @RequestMapping("/update/moxiao")
    @ResponseBody
    public Result updateZt(@RequestBody JSONObject jsonObject) {
        JSONArray djBhArray = jsonObject.getJSONArray("djBh");
        String currentFormattedDateTime = jsonObject.getString("currentFormattedDateTime");
        int zt = jsonObject.getInteger("zt");
        currentFormattedDateTime = currentFormattedDateTime.replace("/", "-");
        int gzmDcMxcs = jsonObject.getInteger("gzmDcMxcs");
        String userName = jsonObject.getString("userName");
        List<User> users = materialServer.selectUser(userName);
        String bmmc = users.get(0).getBmmc();
        String name = users.get(0).getName();
        if (djBhArray != null && !djBhArray.isEmpty()) {
            List<String> djBhList = djBhArray.toJavaList(String.class);
            for (String djBh : djBhList) {
                moXiaoService.updateZt(djBh, userName, name, bmmc, currentFormattedDateTime, zt, gzmDcMxcs);
                moXiaoService.updateZTB(djBh, zt);
            }
            return Result.success("200", "更改成功");
        }
        return Result.failure("500", "更改失败");
    }

    @RequestMapping("/wj/moxiao")
    @ResponseBody
    public Result wjZt(@RequestBody JSONObject jsonObject) {
        JSONArray djBhArray = jsonObject.getJSONArray("djBh");
        int zt = jsonObject.getInteger("zt");
        if (djBhArray != null && !djBhArray.isEmpty()) {
            List<String> djBhList = djBhArray.toJavaList(String.class);
            boolean isOk = true;
            for (String djBh : djBhList) {
                int i = moXiaoService.updateZTB(djBh, zt);
                if (i == 0) {
                    isOk = false;
                }
            }
            if (isOk) {
                return Result.success("200", "更改成功");
            }
            return Result.failure("500", "更改失败");

        }
        return Result.failure("500", "更改失败");
    }

    /**
     * 将磨削记录插入
     */
    @RequestMapping("/insert/moxiao")
    @ResponseBody
    public Result insertYC(@RequestBody JSONObject jsonObject) throws ParseException {
        JSONArray djBhArray = jsonObject.getJSONArray("requestData");
        String gx = jsonObject.getString("gx");
        String sb = jsonObject.getString("sb");
        String banZu = jsonObject.getString("banZu");
        String bz = jsonObject.getString("bz");
        String currentFormattedDateTime = jsonObject.getString("currentFormattedDateTime");
        currentFormattedDateTime = currentFormattedDateTime.replace("/", "-");
        Integer zt = jsonObject.getInteger("zt");
        String userName = jsonObject.getString("userName");
        List<User> users = materialServer.selectUser(userName);
        String bmmc = users.get(0).getBmmc();
        String name = users.get(0).getName();
        Integer id = moXiaoService.getMcMxAutoid();
        if (id != null) {
            id++;
        } else {
            id = 1;
        }
        int k = moXiaoService.insertMcMx(id, gx, sb, banZu, bz, 3, 0, userName, name, bmmc, currentFormattedDateTime);

        if (djBhArray != null && !djBhArray.isEmpty() && djBhArray.getJSONObject(0).containsKey("djBh")) {
            Integer agzmDcMxcs = null;
            for (int i = 0; i < djBhArray.size(); i++) {
                JSONObject requestDataObj = djBhArray.getJSONObject(i);
                String k3WlBm = requestDataObj.getString("k3WlBm");
                String k3Mc = requestDataObj.getString("k3Mc");
                String lx = requestDataObj.getString("lb");
                String zh = requestDataObj.getString("zh");
                BigDecimal scCpzj = requestDataObj.getBigDecimal("scCpzj");
                BigDecimal gzmBfZj = requestDataObj.getBigDecimal("gzmBfZj");
                BigDecimal gzmCcdXx = requestDataObj.getBigDecimal("gzmCcdXx");
                BigDecimal gzmCcdSx = requestDataObj.getBigDecimal("gzmCcdSx");
                BigDecimal csWj = requestDataObj.getBigDecimal("csWj");
                String djBh = requestDataObj.getString("djBh");
                String lb = requestDataObj.getString("lb");
                String bcMxsj = currentFormattedDateTime;
                BigDecimal bcMxzj = requestDataObj.getBigDecimal("bcCpzj");
                BigDecimal zjMxzj = requestDataObj.getBigDecimal("scCpzj");
                String zjMxsj = requestDataObj.getString("scMoxiaoDate");
                String ghZq = "0";
                if (zjMxsj != null && zjMxzj != null) {
                    K3FlXx k3FlXx = k3WlXxSQServer.selectK3FlXxDjBh(djBh);
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date dateBcMoxiao = sdf.parse(bcMxsj);
                    Date dateScMoxiao = sdf.parse(zjMxsj);
                    // 计算日期差值
                    long difference = Math.abs(dateBcMoxiao.getTime() - dateScMoxiao.getTime());
                    long daysDifference = difference / (24 * 60 * 60 * 1000);
                    // 转换差值为字符串
                    ghZq = String.valueOf(daysDifference);
                }
                zjMxzj = bcMxzj;
                zjMxsj = bcMxsj;
                agzmDcMxcs = requestDataObj.getInteger("agzmDcMxcs");
                // 判定 djbh 是否为空字符串或 null
                if (djBh != null && !djBh.isEmpty()) {
                    agzmDcMxcs++;
//                    Date date = new Date();
//                    moXiaoService.insertMcMx()
                    moXiaoService.updateZt(djBh, userName, name, bmmc, currentFormattedDateTime, zt, agzmDcMxcs);
                    moXiaoService.updateMoXiao(djBh, zjMxzj, zjMxsj, bcMxzj, bcMxsj, ghZq);
                    //  子表
                    Integer idList = moXiaoService.getMcMxListAutoid();
                    if (idList != null) {
                        idList++;
                    } else {
                        idList = 1;
                    }
                    int k1 = moXiaoService.insertMcMxList(idList, id, zh, djBh, k3WlBm, k3Mc, 3, lx, agzmDcMxcs, bcMxzj, currentFormattedDateTime, csWj, gzmBfZj, gzmCcdXx, gzmCcdSx, ghZq);

                } else {
                    // 如果 djbh 为空字符串或 null，可以进行相应的处理，或直接跳过当前循环
                    // 例如：continue;
                    continue;
                }
            }
            // 返回处理结果，这里假设你有一个返回 Result 的逻辑

            return Result.success("200", "提交成功");
        } else {
            // 如果数组为空或者不包含 djbh 字段，可以返回相应的结果
            return Result.failure("500", "请求数据为空或不包含 djbh 字段");
        }
    }


    @RequestMapping("/bf/moxiao")
    @ResponseBody
    public Result addBfxx(@RequestBody JSONObject jsonObject) {
        String djbh = jsonObject.getString("djbh");
        String lb = jsonObject.getString("lb");
        String bfsj = jsonObject.getString("bfsj");
        BigDecimal sjbfzj = jsonObject.getBigDecimal("sjbfzj");
        String bfsm = jsonObject.getString("bfsm");
        int bf = moXiaoService.addBfxx(djbh, lb, bfsj, sjbfzj, bfsm);
        if (bf == 1) {
            return Result.success("200", "已经申请报废");
        }
        return Result.failure("500", "申请报废失败");
    }

    /*
     * 通过状态码isdef删除记录，
     * */
    @RequestMapping("/del/moxiao")
    @ResponseBody
    public Result delMoXiao(@RequestBody JSONObject jsonObject) {
        JSONArray djBhArray = jsonObject.getJSONArray("djBh");
        int isDel = jsonObject.getInteger("isDel");
        if (djBhArray != null && !djBhArray.isEmpty()) {
            List<String> djBhList = djBhArray.toJavaList(String.class);
            for (String djBh : djBhList) {
                moXiaoService.delMoXiao(djBh, isDel);
            }
            return Result.success("200", "删除成功");
        }
        return Result.failure("500", "删除失败");
    }

    /*
     * 修改的时候根据djbh查询的数据，用来详细数据
     * */
    @RequestMapping("/select/moxiao")
    @ResponseBody
    public List<MoxiaoDto> selectMoXiaoBydjbh(@RequestBody JSONObject jsonObject) {
        JSONArray djBhArray = jsonObject.getJSONArray("djBh");
        JSONArray agzmDcMxcses = jsonObject.getJSONArray("agzmDcMxcs");
        List<MoxiaoDto> moxiaoDtoList = new ArrayList<>();
        if (djBhArray != null && !djBhArray.isEmpty() && agzmDcMxcses != null && !agzmDcMxcses.isEmpty()) {
            List<String> djBhList = djBhArray.toJavaList(String.class);
            List<Integer> agzmDcMxcsList = agzmDcMxcses.toJavaList(Integer.class);
            // Assuming djBhList and agzmDcMxcsList have the same size
            for (int i = 0; i < djBhList.size(); i++) {
                String djBh = djBhList.get(i);
                int agzmDcMxcs = agzmDcMxcsList.get(i);
                List<K3FlXx> k3FlXxList = moXiaoService.selectMoXiaoBydjbh(djBh, agzmDcMxcs);
                for (K3FlXx k3FlXx : k3FlXxList) {
                    // 进行字段处理
                    agzmDcMxcs = k3FlXx.getGzmDcMxcs();
                    String lb = k3FlXx.getLx();
                    BigDecimal scCpzj = k3FlXx.getZjMxzj();
                    String k3Mc = k3FlXx.getK3Mc();
                    BigDecimal csWj = k3FlXx.getCsWj();
                    BigDecimal gzmBfZj = k3FlXx.getGzmBfZj();
                    BigDecimal gzmCcdXx = k3FlXx.getGzmCcdXx();
                    BigDecimal gzmCcdSx = k3FlXx.getGzmCcdSx();
                    String ghZq = k3FlXx.getGhZq();
                    // 假设需要取出 k3FlXx 的一些字段，然后创建对应的 MoxiaoDto 对象
                    MoxiaoDto moxiaoDto = new MoxiaoDto();
                    moxiaoDto.setAgzmDcMxcs(agzmDcMxcs);
                    moxiaoDto.setCsWj(csWj);
                    moxiaoDto.setGzmBfZj(gzmBfZj);
                    moxiaoDto.setLb(lb);
                    moxiaoDto.setK3Mc(k3Mc);
                    moxiaoDto.setGzmCcdSx(gzmCcdSx);
                    moxiaoDto.setGzmCcdXx(gzmCcdXx);
                    moxiaoDto.setGhZq(ghZq);
                    moxiaoDto.setDjBh(djBh);
                    moxiaoDto.setScCpzj(scCpzj);// 替换为实际字段
                    // 替换为实际字段

                    // 将处理后的对象添加到集合中
                    moxiaoDtoList.add(moxiaoDto);
                }
            }

            return moxiaoDtoList;
        }
        return null;
    }

    @RequestMapping("/add/ycjl")
    @ResponseBody
    public Result addYcjl(@RequestBody JSONObject jsonObject) {
        String djBh = jsonObject.getString("djBh");
        String ycqkjl = jsonObject.getString("ycqkjl");
        String djZt = jsonObject.getString("djZt");
        int agzmDcMxcs = jsonObject.getInteger("agzmDcMxcs");
        String xgr = jsonObject.getString("userName");
        List<User> users = materialServer.selectUser(xgr);
        String xgbm = users.get(0).getBmmc();
        String xgsj = jsonObject.getString("xgsj");
        xgsj = xgsj.replace("/", "-");
        int zt = 4;
        int yczt = moXiaoService.updateZTB(djBh, zt);
        int ycjl = moXiaoService.updateYcjl(djBh, agzmDcMxcs, xgr, xgbm, xgsj, djZt, ycqkjl);
        if (ycjl == 1 && yczt == 1) {
            return Result.success("200", "报告异常成功");
        }
        return Result.failure("500", "报告异常失败");
    }

    /**
     * 叠加磨削次数
     */
    @RequestMapping("/add/mxcs")
    @ResponseBody
    public Result addMxcs(@RequestBody JSONObject jsonObject) {
        JSONArray djBhArray = jsonObject.getJSONArray("djBh");
        String agzmDcMxcs = jsonObject.getString("agzmDcMxcs");
        String bcMoxiaoDate = jsonObject.getString("bcMoxiaoDate");
        BigDecimal bcCpzj = jsonObject.getBigDecimal("bcCpzj");
        if (djBhArray != null && !djBhArray.isEmpty()) {
            List<String> djBhList = djBhArray.toJavaList(String.class);
            for (String djBh : djBhList) {
                moXiaoService.updateLjcs(djBh, agzmDcMxcs, bcMoxiaoDate, bcCpzj);
            }
            return Result.success("200", "磨削增加成功");
        }
        return Result.failure("500", "磨削增加失败");
    }

    //   回显页面
    @RequestMapping("/zh/select/moxiao")
    @ResponseBody
    public List<McMxList> zhSelectMoXiao(@RequestBody JSONObject jsonObject) {
        Integer id = jsonObject.getInteger("id");
        List<McMxList> mcMxList = moXiaoService.getMcMxList(id);
        return mcMxList;
    }

    @RequestMapping("/up/Date/McMx")
    @ResponseBody
    public Result upDateMcMx(@RequestBody JSONObject jsonObject) {
        McMx mx = jsonObject.getObject("form", McMx.class);
        String userName = jsonObject.getString("userName");
        String currentFormattedDateTime = jsonObject.getString("currentFormattedDateTime");
        List<User> users = materialServer.selectUser(userName);
        String bmmc = users.get(0).getBmmc();
        String name = users.get(0).getName();
        mx.setXgrGh(userName);
        mx.setXgrXm(name);
        mx.setXgrBm(bmmc);
        mx.setXgSj(currentFormattedDateTime);
        int k = moXiaoService.upDateMcMx(mx);
//        前端传递的主表id
        Integer id = jsonObject.getInteger("id");
//        根据主表id查看对应子表
        List<McMxList> mcMxList1 = moXiaoService.getMcMxList(id);
        for (McMxList mcMxList : mcMxList1) {
//            修改信息表的状态
            int i = mcYcService.upDateMcK3FlDgXxZt(mcMxList.getDjBh(), 2);
            int gzmDcMxcs = mcMxList.getGzmDcMxcs();
            if (gzmDcMxcs != 0) {
                gzmDcMxcs--;
            }
            moXiaoService.upDateGzmDcMxcs(mcMxList.getDjBh(), gzmDcMxcs);
        }
        boolean isOK = true;
        JSONArray formDataList = jsonObject.getJSONArray("formDataList");
        if (!formDataList.isEmpty()) {
            int i1 = moXiaoService.deleteMcMxListParentId(id);
            for (int i = 0; i < formDataList.size(); i++) {
                JSONObject formData = formDataList.getJSONObject(i);
                McMxList mcMxList = formData.toJavaObject(McMxList.class);
                Integer mcMxListAutoid = moXiaoService.getMcMxListAutoid();
                if (mcMxListAutoid != null) {
                    mcMxListAutoid++;
                } else {
                    mcMxListAutoid = 1;
                }
                String zh = mcMxList.getZh();
                String djBh = mcMxList.getDjBh();
                String k3WlBm = mcMxList.getK3WlBm();
                String k3Mc = mcMxList.getK3Mc();
                String lx = mcMxList.getLx();
                int gzmDcMxcs = mcMxList.getGzmDcMxcs();
                BigDecimal bcMxzj = mcMxList.getBcMxzj();
                String bcMxsj = mcMxList.getBcMxsj();
                BigDecimal csWj = mcMxList.getCsWj();
                BigDecimal gzmBfZj = mcMxList.getGzmBfZj();
                BigDecimal gzmCcdSx = mcMxList.getGzmCcdSx();
                BigDecimal gzmCcdXx = mcMxList.getGzmCcdXx();
                String ghZq = mcMxList.getGhZq();
                mcYcService.upDateMcK3FlDgXxZt(djBh, 3);
                K3FlXx k3FlXx = k3WlXxSQServer.selectK3FlXxDjBh(djBh);
                int mxcs = k3FlXx.getGzmDcMxcs() + 1;
                moXiaoService.upDateGzmDcMxcs(djBh, mxcs);
                int i2 = moXiaoService.insertMcMxList(mcMxListAutoid, id, zh, djBh, k3WlBm, k3Mc, 3, lx, gzmDcMxcs, bcMxzj, bcMxsj, csWj, gzmBfZj, gzmCcdXx, gzmCcdSx, ghZq);
                if (i2 == 0) {
                    isOK = false;
                }
            }
        }

        if (isOK) {
            return Result.success("200", "保存成功");

        }
        return Result.failure("500", "保存失败");
    }

    //                    int i = moXiaoService.updateZTB(djBh, zt);
//    审核
    @RequestMapping("/up/Date/McMx/Sh")
    @ResponseBody
    public Result upDateMcMxSh(@RequestBody JSONObject jsonObject) {
        String currentFormattedDateTime = jsonObject.getString("currentFormattedDateTime");
        currentFormattedDateTime = currentFormattedDateTime.replace("/", "-");
        JSONArray idArray = jsonObject.getJSONArray("id");
        Integer zt = jsonObject.getInteger("zt");
        String userName = jsonObject.getString("userName");
        List<User> users = materialServer.selectUser(userName);
        String bmmc = users.get(0).getBmmc();
        String name = users.get(0).getName();
        boolean isOk = true;
        if (!idArray.isEmpty()) {
            for (Object currentIdObj : idArray) {
                int currentId = (Integer) currentIdObj;
                int i1 = moXiaoService.upDateMcMxSh(currentId, zt, 1, userName, name, bmmc, currentFormattedDateTime);
                if (i1 == 0) {
                    isOk = false;
                }
                List<McMxList> mcMxList = moXiaoService.getMcMxList(currentId);
                for (McMxList mcList : mcMxList) {
                    int yczt = moXiaoService.updateZTB(mcList.getDjBh(), zt);
                    if (yczt == 0) {
                        isOk = false;
                    }
                }
            }
        }
        if (isOk) {
            return Result.success("200", "审核成功");
        }
        return Result.failure("500", "审核失败");
    }

    @RequestMapping("/up/Date/McMx/Sh/QS")
    @ResponseBody
    public Result upDateMcMxShQs(@RequestBody JSONObject jsonObject) {
        String currentFormattedDateTime = jsonObject.getString("currentFormattedDateTime");
        currentFormattedDateTime = currentFormattedDateTime.replace("/", "-");
        Integer zt = jsonObject.getInteger("zt");
        String userName = jsonObject.getString("userName");
        List<User> users = materialServer.selectUser(userName);
        String bmmc = users.get(0).getBmmc();
        String name = users.get(0).getName();
        JSONArray id = jsonObject.getJSONArray("id");
        if (!id.isEmpty()) {
            for (int i = 0; i < id.size(); i++) {
//                获取单据id
                int d = (int) id.get(i);
//                获取单据id的子表所有单件编号
                List<McMxList> mcMxList = moXiaoService.getMcMxList(d);
                for (McMxList mcMxList1 : mcMxList) {
                    String djBh = mcMxList1.getDjBh();
//                    K3FlXx k3FlXx = k3WlXxSQServer.selectK3FlXxDjBh(djBh);
                    int gzmDcMxcs = mcMxList1.getGzmDcMxcs();
//                    int gzmDcMxcs = k3FlXx.getGzmDcMxcs();
//                    查询有没有工作次数和单据编号相同的
                    Integer cite = hcxxService.isCite(gzmDcMxcs, djBh);
                    if (cite == null||cite==0) {
                        int yczt = moXiaoService.updateZTB(djBh, zt);
                        int i1 = moXiaoService.upDateMcMxSh(d, zt, 0, "", "", "", "");

                    }else {
                        return Result.failure("500", "单据中的辊号已被引用，无法弃审");
                    }
                }


            }
        }
        return Result.success("200", "弃审成功");

    }
}


